package com.awenhui.demo.core.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.support.ManagedMap;

import java.util.Date;
import java.util.HashMap;

/**
 * @author yuxf
 * @version 1.0
 * @date 2020/10/16 17:56
 * https://www.jianshu.com/p/278ad96dc7f3
 */
public class JjwtUtils {
    //ConfigurationProperties
    //https://blog.csdn.net/yusimiao/article/details/97622666

    /**
     * 创建jwt token
     *
     * @param secret       密钥
     * @param expireSecond 过期秒数
     * @param subject
     * @param claims       自定义参数值，setClaims会覆盖前面的值，故要放在最前面
     * @return
     */
    public static String cteateJwtToken(String secret, String subject, int expireSecond, HashMap<String, Object> claims) {
        if (claims == null) claims = new HashMap<>();
        long exp = System.currentTimeMillis() + expireSecond * 1000;
        Date expire = new Date(exp);
        String token = Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(new Date())
                .claim("name", "yuxf")
                .setExpiration(expire)
                .signWith(SignatureAlgorithm.HS256, secret).compact();
        return token;
    }

    /**
     * token是否过期
     * @param secret
     * @param token
     * @return
     */
    public static boolean isTokenExpired(String secret, String token) {
        return getClaims(secret, token).getExpiration().before(new Date());
    }

    /**
     * 验证token
     *
     * @return
     */
    public static boolean validateToken() {
        return false;
    }


    public static Claims getClaims(String secret, String token) {
        Claims clainms = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        return clainms;
    }


}
